<script setup>
import { ref, onMounted, computed } from "vue";
import axios from "axios";

// Reactive state
const message = ref("");
const plates = ref([]);
const selectedDate = ref("");
const selectedProvince = ref("");
const showProvinceDropdown = ref(false);
const timeRangePlatesInfos = ref({});
const dailyRecords = ref([]);
const provinceRecords = ref([]);
const currentPage = ref("home");
const parkingStatus = ref("正常");
const activePlates = ref([]);
const showDailyNotFound = ref(false);
const showProvinceNotFound = ref(false);
const selectedDateRange1 = ref(new Date().toLocaleString('zh-CN', {
  timeZone: 'Asia/Shanghai', // 东八区时区标识符
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
}).replaceAll('/', '-'));
const selectedDateRange2 = ref(new Date().toLocaleString('zh-CN', {
  timeZone: 'Asia/Shanghai', // 东八区时区标识符
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
}).replaceAll('/', '-'));

// Fee settings
const feeSettings = ref({
  feeWithin1Hour: 5,
  feeAfter1Hour: 2,
  feeWithin24Hours: 50,
});

// Computed properties
const today = computed(() => {
  return new Date().toISOString().split('T')[0];
});

const formattedDateRange1 = computed({
  get() {
    return selectedDateRange1.value;
  },
  set(value) {
    if (validateDate(value)) {
      selectedDateRange1.value = value;
      // Auto-adjust end date if needed
      if (new Date(value) > new Date(selectedDateRange2.value)) {
        selectedDateRange2.value = value;
      }
    }
  }
});

const formattedDateRange2 = computed({
  get() {
    return selectedDateRange2.value;
  },
  set(value) {
    if (validateDate(value)) {
      selectedDateRange2.value = value;
      // Ensure end date is not before start date
      if (new Date(value) < new Date(selectedDateRange1.value)) {
        selectedDateRange2.value = selectedDateRange1.value;
      }
    }
  }
});

// Methods
const validateDate = (dateValue) => {
  const todayDate = new Date(today.value);
  const selectedDate = new Date(dateValue);

  if (selectedDate > todayDate) {
    showToast("日期不能超过今天");
    return false;
  }
  return true;
};

const showToast = (msg) => {
  message.value = msg;
  setTimeout(() => message.value = "", 3000);
};

const fetchPlates = async () => {
  try {
    const response = await axios.get("http://localhost:8000/plates/active");
    plates.value = response.data.plates;
  } catch (error) {
    console.error("获取车牌记录失败:", error);
    showToast("获取车牌记录失败");
  }
};

const fetchActivePlates = async () => {
  try {
    const response = await axios.get("http://localhost:8000/plates/active");
    activePlates.value = response.data.plates;
  } catch (error) {
    console.error("获取车位状态失败:", error);
    showToast("获取车位状态失败");
  }
};

const fetchTimeRangePlatesInfo = async () => {
  if (!selectedDateRange1.value || !selectedDateRange2.value) {
    showToast("请选择日期");
    return;
  }
  try {
    timeRangePlatesInfos.value = {};
    const response = await axios.get(
      `http://localhost:8000/plates/getTimeRangeInfo?start_time=${selectedDateRange1.value}&end_time=${selectedDateRange2.value}`
    );
    timeRangePlatesInfos.value = response.data;
  } catch (error) {
    console.error("获取车位时间段信息失败:", error);
    showToast("获取车位时间段信息失败");
  }
};

const downloadData = async () => {
  if (!selectedDateRange1.value || !selectedDateRange2.value) {
    showToast("请选择日期");
    return;
  }
  try {
    const response = await axios.get(
      `http://localhost:8000/plates/export_excel?start_time=${selectedDateRange1.value}&end_time=${selectedDateRange2.value}`,
      { responseType: "blob" }
    );

    const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });

    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = downloadUrl;
    link.setAttribute("download", `停车数据_${selectedDateRange1.value}_至_${selectedDateRange2.value}.xlsx`);
    document.body.appendChild(link);
    link.click();
    link.remove();
    window.URL.revokeObjectURL(downloadUrl);
  } catch (error) {
    console.error("下载数据失败:", error);
    showToast("下载数据失败");
  }
};

const calculateCurrentParkingTime = (enterTime) => {
  const enter = new Date(enterTime);
  const now = new Date();
  const diff = now - enter;
  if (diff < 0) return "异常";
  const hours = Math.floor(diff / 3600000);
  const minutes = Math.floor((diff % 3600000) / 60000);
  return `${hours}小时${minutes}分钟`;
};

const calculateCurrentParkingTimeBysecend = (diff) => {
  if (diff < 0) return "异常";
  const hours = Math.floor(diff / 3600);
  const minutes = Math.floor((diff % 3600) / 60);
  return `${hours}小时${minutes}分钟`;
};

const calculateCurrentFee = (enterTime) => {
  const enter = new Date(enterTime);
  const now = new Date();
  let diff = now - enter;
  if (diff < 0) return 0;
  let seconds = Math.floor(diff / 1000);
  let hours = seconds / 3600;

  return calculateFeeFromHours(hours);
};

const calculateCurrentFeeBysecend = (diff) => {
  let hours = diff / 3600;
  return calculateFeeFromHours(hours);
};

const calculateFeeFromHours = (hours) => {
  const settings = feeSettings.value;

  if (hours <= 1) {
    return settings.feeWithin1Hour;
  } else if (hours <= 24) {
    let extra_hours = hours - 1;
    let half_hours = Math.floor(extra_hours * 2);
    let fee = settings.feeWithin1Hour + half_hours * settings.feeAfter1Hour;
    return Math.min(fee, settings.feeWithin24Hours);
  } else {
    let days = Math.floor(hours / 24);
    let remaining_hours = hours % 24;
    let fee = days * settings.feeWithin24Hours;

    if (remaining_hours <= 1) {
      fee += settings.feeWithin1Hour;
    } else {
      let extra_hours = remaining_hours - 1;
      let half_hours = Math.floor(extra_hours * 2);
      fee += settings.feeWithin1Hour + half_hours * settings.feeAfter1Hour;
      fee = Math.min(fee, (days + 1) * settings.feeWithin24Hours);
    }
    return fee;
  }
};

const loadSettings = async () => {
  try {
    const response = await axios.get("http://localhost:8000/plates/load_fee_settings");
    feeSettings.value = {
      feeWithin1Hour: response.data.fee_within_1_hour,
      feeAfter1Hour: response.data.fee_after_1_hour,
      feeWithin24Hours: response.data.fee_within_24_hours
    };
  } catch (error) {
    console.error("加载设置失败:", error);
    showToast("加载设置失败，使用默认值");
  }
};

// Lifecycle hooks
onMounted(() => {
  fetchPlates();
  fetchActivePlates();
  fetchTimeRangePlatesInfo();
  loadSettings();
});
</script>

<template>
  <div class="container-fluid p-4" style="min-height: 100vh">
    <!-- Toast Message -->
    <div v-if="message" class="toast-container position-fixed top-0 end-0 p-3">
      <div class="toast show" role="alert">
        <div class="toast-body bg-danger text-white">
          {{ message }}
        </div>
      </div>
    </div>

    <h1 class="text-center mb-4">费用分析</h1>
    <div class="table-responsive mb-5">
      <table class="table table-striped table-hover">
        <thead class="table-dark">
          <tr>
            <th scope="col">车牌号</th>
            <th scope="col">进入时间</th>
            <th scope="col">当前停车时间</th>
            <th scope="col">应缴费用</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="plate in activePlates" :key="plate.id">
            <td>{{ plate.plate_number }}</td>
            <td>{{ plate.enter_time }}</td>
            <td>{{ calculateCurrentParkingTime(plate.enter_time) }}</td>
            <td>{{ calculateCurrentFee(plate.enter_time) }} 元</td>
          </tr>
          <tr v-if="activePlates.length === 0">
            <td colspan="4" class="text-center text-muted">暂无数据</td>
          </tr>
        </tbody>
      </table>
    </div>

    <h1 class="text-center mb-4">统计</h1>
    <div class="row mb-4 g-3 align-items-end">
      <div class="col-md-6">
        <label for="dateSelect" class="form-label">选择日期范围：</label>
        <div class="input-group">
          <input type="date" id="dateSelect1" class="form-control" v-model="formattedDateRange1"
            :max="formattedDateRange2 || today" />
          <span class="input-group-text">至</span>
          <input type="date" id="dateSelect2" class="form-control" v-model="formattedDateRange2"
            :min="formattedDateRange1" :max="today" />
          <button class="btn btn-primary" @click="fetchTimeRangePlatesInfo">
            查询
          </button>
        </div>
      </div>
      <div class="col-md-3">
        <button class="btn btn-success" @click="downloadData">
          <i class="bi bi-download me-2"></i>下载数据
        </button>
      </div>
      <div class="col-md-3">
        <div class="card bg-light">
          <div class="card-body py-2">
            <h5 class="card-title mb-0">总费用: {{ timeRangePlatesInfos.cost_sum || 0 }} 元</h5>
          </div>
        </div>
      </div>
    </div>

    <div class="table-responsive mb-5">
      <h4 class="mb-3">已结算记录</h4>
      <table class="table table-striped table-hover">
        <thead class="table-dark">
          <tr>
            <th scope="col">车牌号</th>
            <th scope="col">进入时间</th>
            <th scope="col">离开时间</th>
            <th scope="col">停车时长</th>
            <th scope="col">已交费用</th>
            <th scope="col">状态</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(plate, index) in timeRangePlatesInfos.data" :key="'settled-' + index">
            <template v-if="plate && plate.exit_time != null">
              <td>{{ plate.plate_number }}</td>
              <td>{{ plate.enter_time }}</td>
              <td>{{ plate.exit_time }}</td>
              <td>{{ calculateCurrentParkingTimeBysecend(plate.parking_duration) }}</td>
              <td>{{ plate.cost }} 元</td>
              <td><span class="badge bg-success">已结算</span></td>
            </template>
          </tr>
          <tr
            v-if="!timeRangePlatesInfos.data || timeRangePlatesInfos.data.filter(p => p && p.exit_time != null).length === 0">
            <td colspan="6" class="text-center text-muted">暂无已结算记录</td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="table-responsive">
      <h4 class="mb-3">在车位记录</h4>
      <table class="table table-striped table-hover">
        <thead class="table-dark">
          <tr>
            <th scope="col">车牌号</th>
            <th scope="col">进入时间</th>
            <th scope="col">停车时长</th>
            <th scope="col">应缴费用</th>
            <th scope="col">状态</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(plate, index) in timeRangePlatesInfos.data" :key="'active-' + index">
            <template v-if="plate && plate.exit_time == null">
              <td>{{ plate.plate_number }}</td>
              <td>{{ plate.enter_time }}</td>
              <td>{{ calculateCurrentParkingTimeBysecend(plate.parking_duration) }}</td>
              <td>{{ plate.cost }} 元</td>
              <td><span class="badge bg-warning text-dark">在车位</span></td>
            </template>
          </tr>
          <tr
            v-if="!timeRangePlatesInfos.data || timeRangePlatesInfos.data.filter(p => p && p.exit_time == null).length === 0">
            <td colspan="5" class="text-center text-muted">暂无在车位记录</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<style scoped>
.toast-container {
  z-index: 1100;
}

.table-responsive {
  margin-bottom: 2rem;
  border-radius: 0.5rem;
  overflow: hidden;
  box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
}

.table {
  margin-bottom: 0;
}

.table th {
  font-weight: 600;
  text-transform: uppercase;
  font-size: 0.8rem;
  letter-spacing: 0.5px;
}

.badge {
  font-weight: 500;
  padding: 0.35em 0.65em;
}

.card {
  border: none;
  border-radius: 0.5rem;
}
</style>